package com.example.springboot01.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.Map;

import com.example.springboot01.pojo.Managers;
import com.example.springboot01.service.LoginService;
import com.example.springboot01.utils.Md5Encrypt;

@RestController
@CrossOrigin
@RequestMapping("/manage")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public Map<String, Object> checkLogin(@RequestBody Managers managers, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession();

        // 防空判断（防止客户端传空或不传）
        if (managers == null || managers.getUsername() == null || managers.getPassw() == null
                || managers.getUsername().isEmpty() || managers.getPassw().isEmpty()) {
            result.put("status", "2");
            result.put("msg", "用户名或密码为空");
            return result;
        }

        // 打印调试（可选）
        System.out.println("request 中的 username：" + managers.getUsername());
        System.out.println("request 中的 passw：" + managers.getPassw());

        // 如果你数据库里是存的 MD5，请加密再查询；如果是明文，先去掉 md5 这一行做测试
        managers.setPassw(Md5Encrypt.md5(managers.getPassw()));

        Managers loginManagers = loginService.findManagers(managers);
        if (loginManagers == null) {
            result.put("status", "0");
            result.put("loginErrMsg", "用户名或密码错误，请重新输入！");
        } else {
            result.put("status", "1");
            result.put("msg", "登录成功");
            session.setAttribute("loginManagers", loginManagers);
            System.out.println("登录成功: " + loginManagers);
        }
        return result;
    }
}
